package com.kye.express.business.main;

import android.app.Application;

import com.allenliu.versionchecklib.core.AllenChecker;
import com.allenliu.versionchecklib.core.VersionParams;
import com.kye.express.business.order.NameCertificationUtils;
import com.kye.express.business.update.CustomVersionDialogActivity;
import com.kye.express.business.update.UpdateService;
import com.kye.express.contract.base.BasePresenter;
import com.kye.express.contract.base.view.ErrorView;
import com.kye.express.contract.base.view.IView;
import com.kye.express.contract.base.view.LoadingView;
import com.kye.model.OpenApiResultObserver;
import com.kye.model.SharedPreferencesConfig;
import com.kye.model.SharedPreferencesManager;
import com.kye.model.UserSession;
import com.kye.model.base.RetrofitManager;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.order.OrderValidationNameCertificationBean;
import com.kye.model.bean.order.scan_code_order.IsCanScanCodeToAddOrder;
import com.kye.model.bean.order.scan_code_order.ScanCodeOrderAddress;
import com.kye.model.bean.user.User;
import com.kye.model.bean.user.request.RequestGetUser;
import com.kye.model.datasource.OrderDataSource;
import com.kye.model.service.UserService;

import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 18/12/2017
 * @updated : 18/12/2017
 * @description : <Description>
 * @update_reason : <UpdateReason>
 */

public interface MainContract {

    interface MainView extends IView, LoadingView, ErrorView {
        void onNeedValidation(OrderValidationNameCertificationBean validation, NameCertificationUtils.CheckListener.Type type);

        void onCanScanCodeAddOrder(String companyCode, ScanCodeOrderAddress addressData);

        void onCanNotScanCodeAddOrder();
    }

    class MainPresenter extends BasePresenter<MainView> {

        private final OrderDataSource mOrderDataSource;

        public MainPresenter() {
            mOrderDataSource = new OrderDataSource();

            UserSession.getInstance()
                    .getUserForRx()
                    .firstOrError()
                    .flatMap(new Function<User, Single<OpenApiResult<User>>>() {
                        @Override
                        public Single<OpenApiResult<User>> apply(User user) throws Exception {
                            return RetrofitManager.getInstance()
                                    .createOpenApiService(UserService.class)
                                    .getUser(new RequestGetUser(user.getPhone()));
                        }
                    })
                    .subscribe(new SingleObserver<OpenApiResult<User>>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onSuccess(OpenApiResult<User> userOpenApiResult) {
                            UserSession.getInstance().setUser(userOpenApiResult.getData());
                        }

                        @Override
                        public void onError(Throwable e) {

                        }
                    });
        }

        public void checkUpdate(Application context) {
            UpdateService.stopService(context);
            AllenChecker.startVersionCheck(
                    context,
                    new VersionParams.Builder()
                            .setRequestUrl("https://res.ky-express.com/android/kyeapp.html")
                            .setCustomDownloadActivityClass(CustomVersionDialogActivity.class)
                            .setService(UpdateService.class)
                            .setDownloadAPKPath(UpdateService.getDownloadApkCachePath())
                            .setShowNotification(false)
                            .setShowDownloadingDialog(true)
                            .build());
        }

        public void checkNameCertification(NameCertificationUtils.CheckListener.Type type) {
            mOrderDataSource.checkNameCertification()
                    .compose(getView().bindToLifecycleDestroy())
                    .doOnSuccess(new Consumer<OpenApiResult<OrderValidationNameCertificationBean>>() {
                        @Override
                        public void accept(OpenApiResult<OrderValidationNameCertificationBean> orderValidationNameCertificationBeanOpenApiResult) throws Exception {
                            SharedPreferencesManager.commit(SharedPreferencesConfig.KEY_NAME_CERTIFICATION, System.currentTimeMillis());
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<OrderValidationNameCertificationBean>() {
                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<OrderValidationNameCertificationBean> result, OrderValidationNameCertificationBean orderValidationNameCertificationBean) {
                            getView().onNeedValidation(orderValidationNameCertificationBean, type);
                        }

                        @Override
                        public void onApiError(OpenApiResult<OrderValidationNameCertificationBean> result, int code, String msg) {
                            getView().onError();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError();
                        }

                        @Override
                        public void onLoaded() {
                            getView().onLoaded();
                        }
                    });
        }

        public void checkCustomCodeForStartScanCodeAddOrder(String customCode) {
            mOrderDataSource.isCanAddOrder(customCode, null)
                    .compose(getView().bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<IsCanScanCodeToAddOrder>() {
                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<IsCanScanCodeToAddOrder> result, IsCanScanCodeToAddOrder isCanScanCodeToAddOrder) {
                            if (isCanScanCodeToAddOrder.isOrdersType()) {
                                final ScanCodeOrderAddress addressData = new ScanCodeOrderAddress();
                                addressData.setContactsPhone(isCanScanCodeToAddOrder.getContactNumber());
                                addressData.setContacts(isCanScanCodeToAddOrder.getContacts());
                                addressData.setIsDefault(isCanScanCodeToAddOrder.isDefault());
                                addressData.setProvince(isCanScanCodeToAddOrder.getProvince());
                                addressData.setCity(isCanScanCodeToAddOrder.getCity());
                                addressData.setArea(isCanScanCodeToAddOrder.getArea());
                                addressData.setAddress(isCanScanCodeToAddOrder.getAddress());
                                addressData.setGuid(isCanScanCodeToAddOrder.getGuid());
                                getView().onCanScanCodeAddOrder(isCanScanCodeToAddOrder.getCompanyCode(), addressData);
                            } else {
                                getView().onCanNotScanCodeAddOrder();
                            }
                        }

                        @Override
                        public void onApiError(OpenApiResult<IsCanScanCodeToAddOrder> result, int code, String msg) {
                            getView().onError(msg);
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError();
                        }

                        @Override
                        public void onLoaded() {
                            getView().onLoaded();
                        }
                    });
        }

    }
}
